﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NPOI;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using System.Drawing;
using DBUtility;
using LumenWorks.Framework.IO.Csv;
using System.Text;

namespace Web
{
    public partial class xiaoshoudd : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                bind();
            }
        }
        public void bind()
        {
            string sql = "select  *   from apc_voucher_yssj  ";
            
            DataTable dt = DBUtility.sqlhelp2.ExcuteDataTable(sql, CommandType.Text, null);

            
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            string mes = "";
            string connectString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            string filepath = GetExcel();
           
            if (!string.IsNullOrEmpty(filepath))
            {
                DataTable dt = ExcelToTable(filepath);
                if (dt != null)
                {
                   DataTableToSQLServer(dt);
                    
                }
                else
                {
                    Response.Write("<script>alert('该表格没有数据！')</script>");
                }
            }

            else
            {
                Response.Write("<script>alert('请选择文件！')</script>");
            }

            bind();
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //BLL.t_dic_gys bll = new BLL.t_dic_gys();
            //if (e.CommandName == "qy")
            //{
            //    string sql = "update t_dic_gys set IsApply='1' where MatShopId='" + e.CommandArgument.ToString() + "'";
            //    bll.ExcuteNonQuery(sql);

            //}
            //else if (e.CommandName == "jy")
            //{
            //    string sql = "update t_dic_gys set IsApply='2' where MatShopId='" + e.CommandArgument.ToString() + "'";
            //    bll.ExcuteNonQuery(sql);

            //}
            //Button1_Click(null, null);
        }


        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            Button1_Click(null, null);
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

            }
        }



        //获得完整的上传文件路径
        protected string GetExcel()
        {
            string fileUrl = "";
            #region 文件上传
            try
            {
                //全名  
                string excelFile = this.FileUpload1.PostedFile.FileName;
                //获取文件名（不包括扩展名）  
                string fileName = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName);
                //扩展名  
                string extentionName = excelFile.Substring(excelFile.LastIndexOf(".") + 1);
                if (fileName == "" || fileName == null)
                {
                    Response.Write("<script>alert('请先选择Excel文件！')</script>");
                    return null;
                }
                if (extentionName == "xls" || extentionName == "XLS")
                {
                    //浏览器安全性限制 无法直接获取客户端文件的真实路径，将文件上传到服务器端 然后获取文件源路径  
                    // 设置上传路径将文件保存到服务器
                    string dateTime = DateTime.Now.Date.ToString("yyyyMMdd");
                    string time = DateTime.Now.ToShortTimeString().Replace(":", "");
                    string newFileName = dateTime + time + DateTime.Now.Millisecond.ToString() + ".xls"; ;
                    //自己创建的文件夹 位置随意 合理即可  
                    fileUrl = Server.MapPath("~/excel1/") + newFileName;
                    this.FileUpload1.PostedFile.SaveAs(fileUrl);
                    //Response.Write("<script>alert('已经上传到服务器文件夹')</script>");
                    return fileUrl;
                }
                else if (extentionName == "xlsx" || extentionName == "XLSX")
                {
                    //浏览器安全性限制 无法直接获取客户端文件的真实路径，将文件上传到服务器端 然后获取文件源路径  
                    // 设置上传路径将文件保存到服务器
                    string dateTime = DateTime.Now.Date.ToString("yyyyMMdd");
                    string time = DateTime.Now.ToShortTimeString().Replace(":", "");
                    string newFileName = dateTime + time + DateTime.Now.Millisecond.ToString() + ".xlsx"; ;
                    //自己创建的文件夹 位置随意 合理即可  
                    fileUrl = Server.MapPath("~/excel1/") + newFileName;
                    this.FileUpload1.PostedFile.SaveAs(fileUrl);
                    //Response.Write("<script>alert('已经上传到服务器文件夹')</script>");
                    return fileUrl;
                }
                else if (extentionName == "csv" || extentionName == "CSV")
                {
                    //浏览器安全性限制 无法直接获取客户端文件的真实路径，将文件上传到服务器端 然后获取文件源路径  
                    // 设置上传路径将文件保存到服务器
                    string dateTime = DateTime.Now.Date.ToString("yyyyMMdd");
                    string time = DateTime.Now.ToShortTimeString().Replace(":", "");
                    string newFileName = dateTime + time + DateTime.Now.Millisecond.ToString() + ".csv"; ;
                    //自己创建的文件夹 位置随意 合理即可  
                    fileUrl = Server.MapPath("~/excel1/") + newFileName;
                    this.FileUpload1.PostedFile.SaveAs(fileUrl);
                    //Response.Write("<script>alert('已经上传到服务器文件夹')</script>");
                    return fileUrl;
                }
                else
                {
                    Response.Write("<script>alert('您上传的不是Excel文件！')</script>");
                    return null;
                }


            }
            catch
            {
                Response.Write("<script>alert('数据上传失败，请重新导入')</script>");
                return null;
            }
            #endregion

        }

        /// <summary>
        /// 导入货物商品到数据库
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="connectString"></param>
        /// <returns></returns>
        public void DataTableToSQLServer(DataTable dt)
        {
            Double yhje = 0;
            DateTime jfrq=DateTime.Now;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string sql = " INSERT INTO apc_yssj ([yssj],[yssj1]) VALUES ('" + dt.Rows[i]["col0"].ToString().Trim() + "','" + dt.Rows[i]["col1"].ToString().Trim() + "') ";
                
                sqlhelp2.ExcuteNonQuery(sql, CommandType.Text, null);
            }
           
        }


        /// <summary>
        /// Excel导入成Datable
        /// </summary>
        /// <param name="file">导入路径(包含文件名与扩展名)</param>
        /// <returns></returns>
        public DataTable ExcelToTable(string file)
        {
            DataTable dt = new DataTable();
            IWorkbook workbook;
            Encoding _encode = Encoding.GetEncoding("utf-8");
            string fileExt = Path.GetExtension(file).ToLower();
            if (fileExt == ".csv")
            {
                Stream stream=new FileStream(file, FileMode.Open, FileAccess.Read);
                using (stream)
                {
                    using (StreamReader input = new StreamReader(stream, _encode))
                    {
                        using (CsvReader csv = new CsvReader(input, false))
                        {
                            int columnCount = csv.FieldCount;
                            for (int i = 0; i < columnCount; i++)
                            {
                                dt.Columns.Add("col" + i.ToString());
                            }

                            while (csv.ReadNextRecord())
                            {
                                DataRow dr = dt.NewRow();
                                for (int i = 0; i < columnCount; i++)
                                {
                                    if (!string.IsNullOrWhiteSpace(csv[i]))
                                    {
                                        dr[i] = csv[i];
                                    }
                                }
                                dt.Rows.Add(dr);
                            }
                            return dt;
                        }

                    }
                }
            }
            else
            {
                using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
                {
                    //XSSFWorkbook 适用XLSX格式，HSSFWorkbook 适用XLS格式
                    if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
                    if (workbook == null) { return null; }
                    ISheet sheet = workbook.GetSheetAt(0);

                    //表头  
                    IRow header = sheet.GetRow(sheet.FirstRowNum);
                    List<int> columns = new List<int>();
                    for (int i = 0; i < header.LastCellNum; i++)
                    {
                        object obj = GetValueType(header.GetCell(i));
                        if (obj == null || obj.ToString() == string.Empty)
                        {
                            dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                        }
                        else
                            dt.Columns.Add(new DataColumn(obj.ToString()));
                        columns.Add(i);
                    }
                    //数据  
                    for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                    {
                        DataRow dr = dt.NewRow();
                        bool hasValue = false;
                        foreach (int j in columns)
                        {
                            dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                            if (dr[j] != null && dr[j].ToString() != string.Empty)
                            {
                                hasValue = true;
                            }
                        }
                        if (hasValue)
                        {
                            dt.Rows.Add(dr);
                        }
                    }
                } 
            }
            
            return dt;
        }


        /// <summary>
        /// 获取单元格类型
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:  
                    return null;
                case CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:  
                    return cell.NumericCellValue;
                case CellType.String: //STRING:  
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:  
                default:
                    return "=" + cell.CellFormula;
            }
        }

        protected void btnsheng_Click(object sender, EventArgs e)
        {
            string mes = "";
            string mes1 = "";
            string mes2 = "";
            int m=0;
            int n=0;

            string sql = " select * from apc_voucher_yssj ";
            DataTable db = DBUtility.sqlhelp2.ExcuteDataTable(sql,CommandType.Text,null);
            if (db.Rows.Count > 0)
            {
                for (int i = 0; i < db.Rows.Count; i++)
                {
                    string str1 = " select  * from Inventory where cInvaddCode='" + db.Rows[i]["define2"].ToString().Trim() + "' ";
                    DataTable dt1 = DBUtility.sqlhelp2.ExcuteDataTable(str1, CommandType.Text, null);
                    if (dt1.Rows.Count < 1)
                    {
                        mes1 = db.Rows[i]["define2"].ToString().Trim() + "#";
                        m++;
                    }
                   
                    if (dt1.Rows.Count >1)
                    {
                        mes2 = db.Rows[i]["define2"].ToString().Trim() + "#";
                        n++;
                    }
                }
                mes = "<script>alert('" + m + "个" + mes1 + "零件号在存货档案里不存在！" + n + "个" + mes2 + "零件号在存货档案里存在多个！')</script>";
               
            }

            if (m == 0 && n == 0)
            {
                SqlConnection conn = new SqlConnection(DBUtility.sqlhelp2.connString);
                conn.Open();
                SqlCommand comm = new SqlCommand("apc_xsdd", conn);
                comm.CommandType = CommandType.StoredProcedure;

                SqlParameter cstatus = comm.Parameters.Add("@cstatus", SqlDbType.VarChar, 100);　　//定义输出参数
                cstatus.Direction = ParameterDirection.Output;　　//参数类型为Output

                //SqlParameter u8BillCode = comm.Parameters.Add("@u8BillCode", SqlDbType.VarChar, 100);　　//定义输出参数
                //cstatus.Direction = ParameterDirection.Output;　　//参数类型为Output

                SqlParameter message = comm.Parameters.Add("@message", SqlDbType.VarChar, 500);　　//定义输出参数
                message.Direction = ParameterDirection.Output;　　//参数类型为Output
                comm.ExecuteNonQuery();
                conn.Close();
                mes = "<script>alert(' 生成成功！')</script>";
                Response.Write(mes);
            }
            else
            {
                Response.Write(mes);
            }

        }

        protected void btndel_Click(object sender, EventArgs e)
        {
            string sql1 = " delete from  apc_voucher_yssj ";
            DBUtility.sqlhelp2.ExcuteNonQuery(sql1, CommandType.Text, null);

            string sql2 = " delete from  apc_yssj ";
            DBUtility.sqlhelp2.ExcuteNonQuery(sql2, CommandType.Text, null);


        }

        protected void btnfresh_Click(object sender, EventArgs e)
        {
            bind();
        }


    }
}